// mq 

const mq = require('./mq/mq');
const event = require('./mq/event');
event.mq = mq;
event.subscribe();

// mq end

// management

require('./management')
    .withSocket()
    .start(); //.open();

// management end

// proxy

var AnyProxy = require('anyproxy');
const exec = require('child_process').exec;

if (!AnyProxy.utils.certMgr.ifRootCAFileExists()) {
    AnyProxy.utils.certMgr.generateRootCA((error, keyPath) => {
        // let users to trust this CA before using proxy
        if (!error) {
            const certDir = require('path').dirname(keyPath);
            console.log('The cert is generated at', certDir);
            const isWin = /^win/.test(process.platform);
            if (isWin) {
                exec('start .', { cwd: certDir });
            } else {
                exec('open .', { cwd: certDir });
            }
        } else {
            console.error('error when generating rootCA', error);
        }
    });
}

const opt = {
    port: 8001,
    rule: require('./myRule'),
    webInterface: {
        enable: true,
        webPort: 8002,
        wsPort: 8003,
    },
    throttle: 10000,
    forceProxyHttps: true,
    silent: false
};

const server = new AnyProxy.ProxyServer(opt);

server.on('ready', () => {
    console.log('-----anyproxy server start-----');
});

server.on('error', e => {
    console.log(`anyproxy error -> ${e}`);
});

server.start();

// proxy end